package com.ms.game.itembox.container;

import java.util.ArrayList;

import com.ms.game.itembox.ChangeItem;
import com.ms.game.itembox.ChangeItemLister;
import com.ms.game.itembox.Item;
import com.ms.game.itembox.ItemBox;
import com.ms.game.itembox.ItemChangeParam;
import com.ms.game.itembox.ItemChangeWay;
import com.ms.game.itembox.message.SBroadCastGetItems;
import com.ms.game.itembox.message.SSimpleItem;
import com.ms.player.Player;
import com.ms.service.error.ErrorCode;
import com.ms.service.module.zone.BasicZone;
import com.ms.service.module.zone.module.BasicZoneModule;
import com.xpec.c4.game.datamanager.BaseDataInfo;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.message.MessageTypes;
import com.xpec.c4.service.contexts.Contexts;
import com.xpec.c4.service.message.MessageAction;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;

/**
 * 補償寶箱
 * @author TW16028
 *
 */
public class ItemGiftBox extends ItemBasic{

	@Override
	public int use(Player player, Item useItem, int useCount, GUID targetGuid, Object... object) {
		return 0;
	}

	@Override
	public int applyItemToDc(BasicZoneModule zoneModule, Player player, Item useItem, GUID orderId, Object... object) {

		ItemExtraSettings extraSettings = useItem.getExtraSetting();
		ChangeItemLister itemLister = new ChangeItemLister();
		for (Item item : extraSettings.getGiftItems()) {
			itemLister.addItem(null, item.getItemId(), item.getCount(), item.getRefineLevel());
		}
		
		zoneModule.getPlayerDataAgent().updatePlayerItemToDC(orderId, player, null, itemLister, ItemChangeWay.ADD_OPEN_GIFT_BOX, 
				player.getZoneId(), player.getZoneId(), null, ItemChangeParam.NO_EXP, this, "updatePlayerItemToDCCallBack",player.getAccountId());
		
		return ErrorCode.SUCCESS;
	}
	
	public void updatePlayerItemToDCCallBack(BaseDataInfo obj, Object... userObject){
		
		BasicZoneModule zoneModule = (BasicZoneModule)Contexts.getModule();
		BasicZone basicZone = zoneModule.getZone();

		ItemChangeParam param = (ItemChangeParam) obj.getData();
		GUID playerId = param.getPlayerId();
		GUID sessionId = PlayerCommonInfoManager.getInstance().getSessionByPlayerGuid(playerId);
		GUID accountID = (GUID)userObject[0];
		if(sessionId == null){
			return;
		}
		
		//移除blockList
		basicZone.removeBlockList(playerId, null);
		
		//送結果給client
		ItemBox.sendUseItemResponseToClient(sessionId, obj.getResultCode(), accountID, playerId);
		
		if (obj.getResultCode() == ErrorCode.SUCCESS) {// 成功
			ArrayList<SSimpleItem> simpleItems = new ArrayList<SSimpleItem>();
			ChangeItemLister itemLister = param.getChangeItemLister();
			for (ChangeItem items : itemLister.getItemMap().values()) {
				simpleItems.add(items.toItem().toClientFormat());
			}

			SBroadCastGetItems broadcast = new SBroadCastGetItems();
			broadcast.setErrorCode(ErrorCode.SUCCESS);
			broadcast.setItems(simpleItems);
			MessageAction.sendMessage(sessionId, MessageTypes.S_ITEM_BROADCAST_GET_ITEMS, broadcast);
			return;
		}
	}
}
